<template>
  <div>
    <div>
      <section class="setion_class">
        <div class="section-title">修改分馆</div>
        <!-- 表单 -->
        <div class="from_post">
          <el-form
            label-width="140px"
            :model="fromData"
            :rules="rules"
            ref="ruleForm"
          >
            <el-form-item label="封面图片" label-width="140px">
              <div class="imgpost">
                <el-upload
                  class="avatar-uploader"
                  name="production"
                  ref="upload"
                  :action="$upUrl"
                  :show-file-list="false"
                  :auto-upload="false"
                  :before-upload="beforeAvatarUpload"
                  :on-change="cropBtn"
                  accept=".jpg,.png,.jpeg"
                >
                  <div class="upimg" v-if="imageUrl" @click.stop="">
                    <img :src="imageUrl" class="avatar" />
                    <div>
                      <div>
                        <i
                          class="el-icon-zoom-in"
                          @click.stop="handlePictureCardPreview(imageUrl)"
                        ></i>
                      </div>
                      <div>
                        <i
                          class="el-icon-delete"
                          @click.stop="handleRemove"
                        ></i>
                      </div>
                    </div>
                  </div>
                  <div v-else class="upback">
                    <div>
                      <i class="el-icon-plus elimg_icon"></i>
                      <div class="elimg_text">添加封面</div>
                    </div>
                  </div>
                </el-upload>
                <div class="img_ps">
                  支持jpg、jepg、png图片，最佳像素比例200*180。大小请控制在1M以内。
                </div>
              </div>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="imageUrl" alt="" />
              </el-dialog>
            </el-form-item>
            <el-form-item
              label="分馆名称"
              label-width="140px"
              prop="branch_name"
            >
              <el-input
                v-model="fromData.branch_name"
                placeholder="请输入分馆名称"
              ></el-input>
            </el-form-item>
            <el-form-item label="分馆简介" label-width="140px" prop="intro">
              <x-wangeditor
                v-model="fromData.intro"
                :isClear="isshow2"
                ref="xwangeditor"
              >
              </x-wangeditor>
            </el-form-item>
            <el-form-item
              label="开放时间"
              label-width="140px"
              prop="dispark_time"
            >
              <el-input
                v-model="fromData.dispark_time"
                placeholder="请输入开放时间"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="交通线路"
              label-width="140px"
              prop="transport_line"
            >
              <el-input
                v-model="fromData.transport_line"
                placeholder="请输入交通线路"
              ></el-input>
            </el-form-item>
            <el-form-item label="分馆地址" label-width="140px">
              <el-cascader
                class="sel_wid"
                v-model="position"
                placeholder="省/市/区"
                :options="options"
                :props="props"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="" label-width="140px" prop="address">
              <el-input
                type="textarea"
                :rows="2"
                placeholder="请输入具体地址"
                v-model="fromData.address"
                resize="none"
                :autosize="{ minRows: 2, maxRows: 4 }"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              label="联系人姓名"
              label-width="140px"
              prop="contacts"
            >
              <el-input
                v-model="fromData.contacts"
                placeholder="请输入名字"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系人电话" label-width="140px" prop="tel">
              <el-input
                v-model="fromData.tel"
                placeholder="请输入有效电话号码"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="借阅须知"
              label-width="140px"
              prop="borrow_notice"
            >
              <el-input
                v-model="fromData.borrow_notice"
                placeholder="请输入借阅须知"
              ></el-input>
            </el-form-item>
            <el-form-item label-width="140px">
              <div style="padding: 48px 0 48px 0" class="btn_el">
                <el-button
                  @click="submitForm('ruleForm')"
                  class="btn_establish"
                >
                  确认
                </el-button>
                <el-button class="btn_cancel" @click="can('ruleForm')"
                  >取消</el-button
                >
              </div>
            </el-form-item>
          </el-form>
        </div>
      </section>
    </div>

    <!-- vueCropper 剪裁图片实现-->
    <x-cropperFixed
      ref="iscropper"
      :uploadImg="uploadImgs"
      @cropPicture="cropPicture"
      :cropImg="cropImg"
    ></x-cropperFixed>
    <el-dialog :visible.sync="cxtPreviewVisible" width="1000px">
      <div class="ql-container ql-snow">
        <div class="ql-editor">
          <div v-html="fromData.intro"></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  name: '',
  data() {
    var validatePhone = (rule, value, callback) => {
      const mobileReg =
        /^(([1][3,4,5,7,8]\d{9})|([0]\d{10,11})|(\d{7,8})|(\d{4}|\d{3})-(\d{7,8}))$/

      const phoneReg = /^\d{3}-\d{8}|\d{4}-\d{7}$/

      if (!value || value === '') {
        callback(new Error('请输入联系方式'))
      } else if (value.length === 11) {
        if (!mobileReg.test(value)) {
          callback(
            new Error('请输入正确的手机号码或者固话号码（固话格式：区号-号码）')
          )
        } else {
          callback()
        }
      } else if (value.length === 12) {
        if (!phoneReg.test(value)) {
          callback(
            new Error('请输入正确的手机号码或者固话号码（固话格式：区号-号码）')
          )
        } else {
          callback()
        }
      } else {
        callback(
          new Error('请输入正确的手机号码或者固话号码（固话格式：区号-号码）')
        )
      }
    }
    return {
      fromData: {
        branch_name: '', //名称
        img: '', //封面图片
        intro: '', //简介
        dispark_time: '', //开放时间（一段文字）
        transport_line: '', //交通线路
        province: '',
        city: '',
        district: '',
        address: '', //详细地址
        tel: '', //联系方式
        contacts: '', //联系人
        borrow_notice: '' //借阅须知
      },
      imageUrl: '',
      dialogVisible: false,
      position: [],
      rules: {
        branch_name: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        img: [{ required: true, message: '请上传封面', trigger: 'blur' }],
        // intro: [{ required: true, message: '请填写简介', trigger: 'change' }],
        dispark_time: [
          { required: true, message: '请填写开放时间', trigger: 'blur' }
        ],
        transport_line: [
          { required: true, message: '请填写交通线路', trigger: 'blur' }
        ],
        // position: [
        //   { required: true, message: '请选择分馆地址', trigger: 'change' }
        // ],
        address: [
          { required: true, message: '请填写详细地址', trigger: 'blur' }
        ],
        tel: [
          {
            validator: validatePhone,
            required: true,
            trigger: 'blur'
          }
        ],
        contacts: [
          { required: true, message: '请填写联系人', trigger: 'blur' }
        ],
        borrow_notice: [
          { required: true, message: '请填写借阅须知', trigger: 'blur' }
        ]
      },
      addelist: '',
      options: [],
      props: {
        // checkStrictly: true, // 是否严格的遵守父子节点不互相关联(官网配置项)
        // value: 'id',
        // label: 'name',
        label: 'name',
        value: 'name',
        children: 'children'
      },
      unimgurl: '',
      cxtPreviewVisible: false, //预览富文本
      isshow2: false,
      cropImg: 'cropImg22',
      uploadImgs: '',
      idObj: ''
    }
  },
  watch: {
    // 要剪裁图片
    uploadImgs(nal, al) {
      this.uploadImgs = nal
    }
  },
  created() {},
  mounted() {
    this.getCityList()
  },
  activated() {
    console.log(this.$route.query.ids)
    this.getList()
  },
  methods: {
    // 获取详情数据
    async getList() {
      this.idObj = this.$route.query.ids
      try {
        let res = await this.request({
          url: '/admin/branchInfo/detail',
          method: 'get',
          loading: false,
          data: {
            id: this.idObj
          }
        })
        if (res) {
          this.fromData = res.content
          this.imageUrl = this.$img(res.content.img[0])

          let { province, city, district } = res.content
          this.position = [province, city, district]
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    //获取地址的数据
    async getCityList() {
      try {
        let res = await this.request({
          url: '/text/getCityAll',
          method: 'get',
          loading: false,
          data: {
            is_letter: 2, //是否需要首字母 1 需要 2 不需要（默认不需要，可不传此参数）
            parent_id: '', //父级id
            is_tree: 1 //是否返回省市区三级树形结构 1是 2否 属性结构只能返回 3 级，若需要街道，获取到省市区后，在根据父级id，获取街道
          }
        })
        if (res) {
          this.options = res.content
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    beforeAvatarUpload(file) {
      console.log(file.size)
      const isJPG = file.type === 'image/jpg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 <= 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //删除封面图
    handleRemove(file, fileList) {
      this.imageUrl = ''
      this.unimgurl = ''
    },
    //选择封面图
    handlePictureCardPreview(img) {
      this.imageUrl = img
      this.dialogVisible = true
    },
    changimg(file, fileList) {
      console.log(fileList)
      let img = URL.createObjectURL(file.raw)
      this.$refs.iscropper.showModal({
        img: img, // 裁剪图片的地址
        outputSize: 0.8, // 裁剪生成图片的质量
        autoCropWidth: 375, // 默认生成截图框宽度
        autoCropHeight: 375, // 默认生成截图框高度
        success: res => {
          console.log(res)
          console.log(res.img.size / 1024 / 1024)
          this.unimgurl = res.img
          this.imageUrl = URL.createObjectURL(res.img)
        }
      })
    },

    cropBtn(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 <= 1
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!')
      } else {
        let that = this
        const fr = new FileReader()
        fr.readAsDataURL(file.raw)
        fr.onload = function () {
          // console.log(fr.result);
          return (that.uploadImgs = fr.result)
        }
        setTimeout(() => {
          this.$refs.iscropper.showModal({
            cutWidth: 200, // 默认生成截图框宽度
            cutHeight: 180, // 默认生成截图框高度
            rate: '200:180',
            file: file.raw
          })
        }, 100)
      }
    },
    // 裁剪返回参数
    cropPicture(imgUrl) {
      this.unimgurl = imgUrl.file
      this.imageUrl = imgUrl.dataURL
    },
    //预览富文本
    onCxtPreview() {
      this.cxtPreviewVisible = true
    },
    // 点击取消
    can(formName) {
      this.$refs[formName].resetFields()
      this.fromData.intro = ''
      this.imageUrl = ''
      this.position = []
      this.$router.push({
        path: '/systemSetting/ourMuseum'
      })
    },
    // 点击提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (
            this.fromData.intro == '' ||
            this.fromData.intro == null ||
            this.fromData.intro == undefined
          ) {
            this.$message.error('请填写分馆简介')
          } else {
            if (this.unimgurl) {
              this.uploadImg(formName)
            } else {
              this.addInfo(formName)
            }
          }
        } else {
          this.$message.warning('请检查输入！')
          return false
        }
      })
    },
    async uploadImg(formName) {
      try {
        let imgRes = await this.request({
          url: '/uploads/files',
          method: 'post',
          dataType: 'blob',
          loading: true,
          data: {
            img: this.unimgurl
          }
        })
        if (imgRes) {
          this.fromData.img = imgRes.content.img
          this.addInfo(formName)
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    // 请求新增接口
    async addInfo(formName) {
      try {
        let res = await this.request({
          url: '/admin/branchInfo/change',
          method: 'post',
          dataType: 'blob',
          loading: true,
          data: {
            ...this.fromData
          }
        })
        if (res) {
          if (res.code == 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            })
            this.$refs[formName].resetFields()
            this.fromData.intro = ''
            this.imageUrl = ''
            this.position = []
            setTimeout(() => {
              this.$router.push({
                path: '/systemSetting/ourMuseum'
              })
            }, 1500)
          }
        }
      } catch (err) {
        this.errorHandler(err)
      }
    },
    handleChange(value) {
      this.fromData.province = value[0]
      this.fromData.city = value[1]
      this.fromData.district = value[2]
    }
  }
}
</script>

<style lang="scss" scoped>
@import './style.scss';
</style>
<style lang="scss">
.el-radio__input.is-checked + .el-radio__label {
  color: $textColorgreen !important;
}
.el-radio__label {
}
.nm-skin-pretty .el-input.is-active .el-input__inner,
.nm-skin-pretty .el-input__inner:focus {
  border-color: $themeColorponti;
}
.el-input__inner:focus {
  border-color: $themeColorponti;
}
.el-switch__core {
  border-radius: 13px;
}
.sew_post {
  .tableScopeSwitch .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
    width: 66px;
    height: 26px;
    line-height: 26px;
    border-radius: 13px;
  }
  /*打开时文字位置设置*/
  .tableScopeSwitch .el-switch__label--right {
    z-index: 1;
    right: -10px; /*不同场景下可能不同，自行调整*/
    top: -2px;
    font-size: 12px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #ffffff;
  }
  /*关闭时文字位置设置*/
  .tableScopeSwitch .el-switch__label--left {
    z-index: 1;
    left: 18px; /*不同场景下可能不同，自行调整*/
    top: -2px;
    font-size: 12px;
    font-family: Microsoft YaHei, Microsoft YaHei-Regular;
    font-weight: 400;
    color: #999999;
  }
  /*显示文字*/
  .tableScopeSwitch .el-switch__label.is-active {
    display: block;
  }
  .tableScopeSwitch.el-switch .el-switch__core,
  .el-switch .el-switch__label {
    width: 66px !important; /*开关按钮的宽度大小*/
    height: 26px;
    line-height: 26px;
  }
  .el-switch__core::after {
    display: flex;
    align-items: center;
    top: 4px;
  }
}

.setion_class {
  .el-select .el-input__inner:focus {
    border-color: $themeColorponti;
  }
  .el-select .el-input.is-focus .el-input__inner {
    border-color: $themeColorponti;
  }
  .el-select .el-input.is-focus .el-input__inner {
    color: $themeColorponti;
  }

  .el-select .el-input__inner:focus {
    color: $themeColorponti;
  }
  .vm-list-item {
    .el-radio .el-radio__inner .el-radio__input {
      display: none !important;
    }
    .el-radio__input {
      display: none !important;
    }
    .el-radio__inner {
      display: none !important;
    }
    .el-radio__label {
    }
    .el-radio__input.is-checked + .el-radio__label {
      color: $themeColorponti !important;
    }
    .el-radio-group {
      display: flex !important;
      flex-direction: row !important;
      align-items: center !important;
    }
    .el-radio {
      width: 100px !important;
      height: 30px !important;
      display: flex !important;
      flex-direction: row !important;
      align-items: center !important;
      justify-content: center !important;
      background: #ededed;
      color: #000000 !important;
    }
    .el-radio__label {
      font-size: 12px !important;
      padding-left: 0 !important;
    }
    .is-checked {
      background: #ffffff;
      border: 1px solid $themeColorponti;
    }
    .raicon {
      position: absolute;
      right: 0;
      bottom: 0;
      color: #fff;
      z-index: 2;
    }
    .is-checked::after {
      content: '';
      width: 0;
      height: 0;
      border-bottom: 18px solid $themeColorponti;
      border-left: 18px solid transparent;
      position: absolute;
      right: 0;
      bottom: 0;
      z-index: 1;
    }
    .is-checked::before {
      content: '\2713';
      // width: 7px;
      // height: 4px;
      // border-left: 2px solid #fff;
      // border-bottom: 2px solid #fff;
      // transform: rotate(-45deg);
      position: absolute;
      right: 0px;
      bottom: 0px;
      z-index: 2;
      color: #fff;
    }
    .el-checkbox__input {
      display: none;
    }
    .el-checkbox .vm-checkbox {
      width: 100px;
      height: 30px;
      background: #fff;
      font-size: 12px;
      font-family: Microsoft YaHei, Microsoft YaHei-Regular;
      font-weight: 400;
      text-align: center;
      color: #000000;
    }
    .el-checkbox__label {
      padding-left: 0px;
      width: 100px;
      height: 30px;
      background: #ededed;
      font-size: 12px;
      font-family: Microsoft YaHei, Microsoft YaHei-Regular;
      font-weight: 400;
      text-align: center;
      color: #000000;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .is-checked {
      .el-checkbox__label {
        background: #fff !important;
      }
    }
  }
}
</style>
